
package ch.hearc.meteo.imp.com.real.com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

import gnu.io.SerialPort;

public class ReaderTimeoutManager implements Runnable
	{

	/*------------------------------------------------------------------*\
	|*							Constructeurs							*|
	\*------------------------------------------------------------------*/

	public ReaderTimeoutManager(SerialPort serialPort, BufferedReader reader, BufferedWriter writer, long timeout)
		{
		this.serialPort = serialPort;
		this.timeout = timeout;
		this.reader = reader;
		this.writer = writer;

		elapsedTime = 0;
		}

	/*------------------------------------------------------------------*\
	|*							Methodes Public							*|
	\*------------------------------------------------------------------*/

	@Override
	public void run()
		{
		System.out.println("[ReaderTimeoutManager] begin");
		while(elapsedTime < timeout)
			{
			try
				{
				Thread.sleep(DT);
				elapsedTime += DT;
				}
			catch (InterruptedException e)
				{
				e.printStackTrace();
				}
			}
		if (!ok)
			{
			System.out.println("[ReaderTimeoutManager] not ok");


			try
				{
				reader.close();
				writer.close();
				serialPort.close();
				}
			catch (IOException e)
				{
				e.printStackTrace();
				}
			}

		System.out.println("[ReaderTimeoutManager] end");
		}

	/*------------------------------*\
	|*				Set				*|
	\*------------------------------*/

	public void setOk(boolean ok)
		{
		this.ok = ok;
		}

	/*------------------------------*\
	|*				Get				*|
	\*------------------------------*/

	/*------------------------------------------------------------------*\
	|*							Methodes Private						*|
	\*------------------------------------------------------------------*/

	/*------------------------------------------------------------------*\
	|*							Attributs Private						*|
	\*------------------------------------------------------------------*/

	//Input
	private SerialPort serialPort;
	private BufferedReader reader;
	private BufferedWriter writer;
	private boolean ok = false;

	//Tools
	private long timeout;
	private long elapsedTime;

	private static final long DT = 100;
	}
